var restify = require('restify');
var assert = require('assert');

// proxy method http client
// receive from localhost:8080/[keyword]
// return http://www.baidu.com/s?wd=[keyword]
function proxy(req, res, next) {
	var path = '/s?wd=' + req.params.keyword;
	console.log('path=' + path);

	var client = restify.createClient({
		url: 'http://www.baidu.com'
	});

	client.get(path, function(err, req) {
		assert.ifError(err);

		req.on('result', function(err, res2) {
			assert.ifError(err);

			var body = '';
			res2.setEncoding('utf8');
			res2.on('data', function(chunk) {
				body += chunk;
			});

			res2.on('end', function() {
				//console.log(body);
				res.end(body);
				console.log('---over---');
			});
		});

	});
}

// get json in fact it sends string at last
function jsonResult(req, res, next) {
	var key = req.params.keyword;
	res.writeHead(200, {
		"Content-Type": "application/json"
	});
	var otherArray = ["item1", "item2"];
	var otherObject = {
		"item1": "item1val",
		"item2": "item2val"
	};
	var json = JSON.stringify({
		anObj: otherObject,
		anArr: otherArray,
		another: "item"
	});
	res.end(json);
}


// get string
function stringResult(req, res, next) {
	var key = req.params.keyword;
	res.writeHead(200, {
		"Content-Type": "text/plain"
	});
	var str = 'you send keyword=' + key;
	res.end(str);
}

var server = restify.createServer();
server.get('/proxy/:keyword', proxy);
//server.head('/:keyword', proxy);

server.get('/json/:keyword', jsonResult);
server.get('/string/:keyword', stringResult);

server.listen(8080, function() {
	console.log('%s listening at %s', server.name, server.url);
});